package com.example.resource.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class ResourseController {

    // 使用 Jwt 进行令牌验证
    @GetMapping("/jwt")
    public String index(@AuthenticationPrincipal Jwt jwt) {
        return String.format("Hello, %s!", jwt.getSubject());
    }

    // 使用 OpenID Connect 进行令牌验证
    @GetMapping("/openid")
    public String index(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
        return String.format("Hello, %s!", (String) principal.getAttribute("sub"));
    }


    @GetMapping("/{tenantId}")
    public String index(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal,
                        @PathVariable("tenantId") String tenantId) {
        String subject = principal.getAttribute("sub");
        return String.format("Hello, %s for %s!", subject, tenantId);
    }

    @GetMapping("/{tenantId}/message")
    public String message(@PathVariable("tenantId") String tenantId) {
        return String.format("secret message for %s", tenantId);
    }


    @PreAuthorize("hasAuthority('SCOPE_messages')")
    @GetMapping("/messages")
    public List<String> getMessages() {
        ArrayList<String> messages = new ArrayList<>();
        messages.add("Message 1");
        messages.add("Message 2");
        messages.add("Message 3");
        return messages;
    }



    @PreAuthorize("principal?.attributes['sub'] == 'foo'")
    @GetMapping("/foo")
    public String forFoosEyesOnly() {
        return "foo";
    }

}
